package com.ruoyi.system.outto.goods.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.goods.DAISHOUWANAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class DAISHOUWANAPIImpl implements DAISHOUWANAPI {

    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner);
        log.info("代售玩添加接口请求参数={}", JSONObject.toJSONString(params));
//        String response = HttpUtils.sendPost("", , "application/json");
        String response = HttpRequest.post("https://www.taohaowan.com/prod-api/system-api/gamesInfo/gameUploaded").body(JSONObject.toJSONString(params)).execute().body();
        log.info("代售玩加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            String data = resultJson.getString("data");
            JSONObject jsonObject = JSONObject.parseObject(data);
            String goodId = jsonObject.getString("goodsId");
            result.put("outId", goodId);
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        // 创建一个Map，用于存储需要排序并加密的数据
        Map<String, Object> dataMap = new TreeMap<>();
        String title = "";
        if (goodsInfoAndAttrValueDto.getDes().length() > 900) {
            title = goodsInfoAndAttrValueDto.getDes().substring(0, 880);
        } else {
            title = goodsInfoAndAttrValueDto.getDes();
        }
        dataMap.put("title", title.replace("+", ""));

        dataMap.put("price", goodsInfoAndAttrValueDto.getPrice().intValue());

        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgs = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));

        if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getTitleImg())) {
            imgs = goodsInfoAndAttrValueDto.getTitleImg() + "," + imgs;
        }
        dataMap.put("pic", imgs);
        dataMap.put("gameAccount", String.valueOf(System.currentTimeMillis()).substring(3));
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        dataMap.put("goodsId", artRecs.get(0).getOutid());
        dataMap.put("appKey", salePartner.getOther());
        dataMap.put("timestamp", time);
        // 遍历排序后的Map，将value值拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            stringBuilder.append(entry.getValue());
        }
        // 执行SHA-256加密
        String encryptedData = DigestUtil.sha256Hex(stringBuilder.toString());
        dataMap.remove("timestamp");
        dataMap.remove("appKey");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appId", salePartner.getSaleKey());
        paramMap.put("timestamp", time);
        paramMap.put("sign", encryptedData);
        paramMap.put("data", dataMap);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-Type", "application/json; charset=UTF-8");
        String response = HttpUtils.sendPost("https://www.taohaowan.com/prod-api/system-api/gamesInfo/gameModify", JSONObject.toJSONString(paramMap), "application/json");
        log.info(response);
        log.info("淘号玩编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);

        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }


        result.put("req", JSONObject.toJSONString(paramMap));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {

        String substring = salePartner.getSaleName();
        if (substring.contains("_")) {
            substring = substring.substring(salePartner.getSaleName().indexOf("_")+1);
        }
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());

        String time = String.valueOf(System.currentTimeMillis() / 1000);
        // 创建一个Map，用于存储需要排序并加密的数据
        Map<String, Object> dataMap = new TreeMap<>();
        String title = "";
        if (goodsInfoAndAttrValueDto.getDes().length() > 900) {
            title = goodsInfoAndAttrValueDto.getDes().substring(0, 880);
        } else {
            title = goodsInfoAndAttrValueDto.getDes();
        }
        dataMap.put("title", title);
        dataMap.put("gameId", interAttr.getInterGameId());
        dataMap.put("gameName", interAttr.getInterGameName());
        dataMap.put("price", goodsInfoAndAttrValueDto.getPrice().intValue());

        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgs = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));

        if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getTitleImg())) {
            imgs = goodsInfoAndAttrValueDto.getTitleImg() + "," + imgs;
        }
        dataMap.put("pic", imgs);
        dataMap.put("gameAccount", String.valueOf(System.currentTimeMillis()).substring(3));
        dataMap.put("healthyStatus", "healthy_status_1");
        dataMap.put("accountSource", "account_source_2");
        dataMap.put("mainIndustry", "main_industry_1");
        dataMap.put("isRecommend", 1);
        if (goodsInfoAndAttrValueDto.getGameName().equals("穿越火线")) {
            dataMap.put("ranking", "ranking_2");
        }

        //开始匹配区服属性
        builderServer(goodsInfoAndAttrValueDto, dataMap, interAttr.getServer());

        //属性
        JSONObject map = new JSONObject();
        JSONArray list = new JSONArray();

        //特殊处理
        if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")){
            map = new JSONObject();
            if(goodsInfoAndAttrValueDto.getGroupName().contains("Steam")) {
                map.put("attributeId", "4807");
                map.put("attributeValue", "steam");
            }else if(goodsInfoAndAttrValueDto.getGroupName().contains("Epic")) {
                map.put("attributeId", "4808");
                map.put("attributeValue", "epic");
            }else {
                map.put("attributeId", "4805");
                map.put("attributeValue", "手机");
            }
            list.add(map);
        }
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, interAttr.getRadioAttr(),map,list);
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, interAttr.getCheckAttr(),map,list);
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, interAttr.getInputAttr(),map,list);



        dataMap.put("gameAttrs", list);
        dataMap.put("appKey", salePartner.getOther());
        dataMap.put("timestamp", time);
        // 遍历排序后的Map，将value值拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            stringBuilder.append(entry.getValue());
        }
        // 执行SHA-256加密
        String encryptedData = DigestUtil.sha256Hex(stringBuilder.toString());
        dataMap.remove("timestamp");
        dataMap.remove("appKey");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appId", salePartner.getSaleKey());
        paramMap.put("timestamp", time);
        paramMap.put("sign", encryptedData);
        paramMap.put("data", dataMap);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-Type", "application/json; charset=UTF-8");
        return paramMap;
    }

    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String inputAttr, JSONObject map, JSONArray list) {

        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                JSONObject att = new JSONObject();
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            if(Objects.isNull(o)){
                                String fieldType = inputTemplate.getFieldType();
                                if(fieldType.equals("number")){
                                    o = 0;
                                }
                            }
                            String oneValue = String.valueOf(o);
                            if (StringUtils.isNotEmpty(oneValue)) {
                                map = new JSONObject();
                                map.put("attributeId",interId);
                                map.put("attributeValue",oneValue);
                                list.add(map);
                            }
                        }
                    }
                }

            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            Integer id = object.getInteger("id");
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                map = new JSONObject();
                map.put("attributeId",id);
                map.put("attributeValue",defaultValue);
                list.add(map);
            }
        }
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String checkAttr, JSONObject map, JSONArray list) {
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object2 : checkJsonList) {
            String interCheckBoxReqsStr2 = object2.getString("interCheckBoxReqs");
            if(StringUtils.isNotEmpty(interCheckBoxReqsStr2)){
                List<JSONObject> jsonObjects3 = JSONObject.parseArray(interCheckBoxReqsStr2, JSONObject.class);
                for(JSONObject object : jsonObjects3) {
                    for (GameAttrTemplate attrTemplate : checkAttrTemplates) {

                        String aavName = attrTemplate.getAavName();
                        for (Field declaredField : declaredFields) {
                            String name = declaredField.getName();
                            if (aavName.equals(name)) {
                                declaredField.setAccessible(true);

                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
                                if(StringUtils.isNotEmpty(interCheckBoxReqsStr)) {
                                    //开始匹配二级属性
                                    List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                    /**
                                     * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                     */
                                    for (JSONObject jsonObject1 : jsonObjects2) {
                                        String[] split1 = oneValue.split(",");
                                        String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                        for (String s : split1) {
                                            if (Objects.equals(s, ydConfigId1)) {
                                                String InterConfigName = jsonObject1.getString("InterConfigName");
//                                    pf_ids+=","+InterConfigId2;
                                                map = new JSONObject();
                                                map.put("attributeId" , jsonObject1.getString("id"));
                                                map.put("attributeValue" , InterConfigName);
                                                list.add(map);
                                            }
                                        }
                                    }
                                }else {
                                    String[] split1 = oneValue.split(",");
                                    String ydConfigId1 = object.getString("YdConfigId");
                                    if(StringUtils.isNotEmpty(ydConfigId1)) {
                                        ydConfigId1 = ydConfigId1.replace(" " , "");
                                    }
                                    for (String s : split1) {
                                        if (Objects.equals(s, ydConfigId1)) {
                                            String InterConfigName = object.getString("InterConfigName");
                                            map = new JSONObject();
                                            map.put("attributeId" , object.getString("id"));
                                            map.put("attributeValue" , InterConfigName);
                                            list.add(map);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }else {
                for (JSONObject object : checkJsonList) {
                    for (GameAttrTemplate attrTemplate : checkAttrTemplates) {

                        String aavName = attrTemplate.getAavName();
                        for (Field declaredField : declaredFields) {
                            String name = declaredField.getName();
                            if (aavName.equals(name)) {
                                declaredField.setAccessible(true);

                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
                                //开始匹配二级属性
                                List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                /**
                                 * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                 */
                                for (JSONObject jsonObject1 : jsonObjects2) {
                                    String[] split1 = oneValue.split(",");
                                    String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                    for (String s : split1) {
                                        if (Objects.equals(s, ydConfigId1)) {
                                            String InterConfigName = jsonObject1.getString("InterConfigName");
                                            map = new JSONObject();
                                            map.put("attributeId",jsonObject1.getString("id"));
                                            map.put("attributeValue",InterConfigName);
                                            list.add(map);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String radioAttr, JSONObject map, JSONArray list) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        for (JSONObject object : jsonObjects) {
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                JSONObject att = new JSONObject();
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
//                            String id = object.getString("id");
                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次
                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId"))?j.getString("YdConfigId").contains(oneValue):"111".contains(oneValue)).collect(Collectors.toList());
                                String interConfigName = object.getString("InterConfigName");
                                String defaultValue = object.getString("defaultValue");
                                if (org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                    if (StringUtils.isNotEmpty(defaultValue)) {
//                                        kghAttribute.setAttribute_id(Integer.parseInt(id));
//                                        kghAttribute.setOption_value(defaultValue);
                                        map = new JSONObject();
                                        map.put("attributeId",object.getString("id"));
                                        map.put("attributeValue",defaultValue);
                                        list.add(map);
                                    }
                                }
//                                if (org.springframework.util.CollectionUtils.isEmpty(twoAttr) && StringUtils.isEmpty(defaultValue)) {
//                                    throw new GlobalException("属性" + interConfigName + " 接口要求必传，但是暂未匹配到，请设置默认值");
//                                }
                                if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                    JSONObject jsonObject2 = twoAttr.get(0);
                                    String InterConfigName = jsonObject2.getString("InterConfigName");
                                    map = new JSONObject();
                                    map.put("attributeId",jsonObject2.getString("id"));
                                    map.put("attributeValue",InterConfigName);
                                    list.add(map);
                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
//            String id = object.getString("id");
            interRadioReqs = object.getString("interRadioReqs");
            jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
            for (JSONObject objects : jsonObjects) {
                if(StringUtils.isNotEmpty(objects.getString("defaultValue"))){
                    map = new JSONObject();
                    map.put("attributeId",objects.getString("id"));
                    map.put("attributeValue",objects.getString("defaultValue"));
                    list.add(map);
                }
            }
        }
        //========================单选属性匹配结束=====================//
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject.getString("interServeReqs");
        String qufuid = "";
        JSONObject oneServerJson = new JSONObject();
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (qufuid.contains(ydServeId)) {
                        oneServerJson = object;
                        params.put("gameareaId", oneServerJson.getString("id"));
                        params.put("gameareaName", oneServerJson.getString("name"));
                        break;
                    }
                }
            }
        } else if(goodsInfoAndAttrValueDto.getGameName().equals("无畏契约")){
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                if(object.getString("YdServeId").contains(goodsInfoAndAttrValueDto.getGroupId().toString())){
                    params.put("gameareaId", object.getString("id"));
                    params.put("gameareaName", object.getString("name"));
                    break;
                }
            }
        } else {
            qufuid = goodsInfoAndAttrValueDto.getServerId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    String interServerRes = object.getString("interServerRes");
                    if(StringUtils.isNotEmpty(interServerRes)) {
                        List<JSONObject> oneServers = JSONObject.parseArray(interServerRes, JSONObject.class);
                        for (JSONObject objects : oneServers) {
                            ydServeId = objects.getString("YdServeId");
                            if (StringUtils.isNotEmpty(ydServeId)) {
                                ydServeId = ydServeId.replace(",", "").replace(" ", "");
                                if (ydServeId.contains(qufuid)) {
                                    oneServerJson = objects;
                                    params.put("gameareaId", oneServerJson.getString("id"));
                                    params.put("gameareaName", oneServerJson.getString("name"));
                                    break;
                                }
                            }
                        }
                    }else {
                        params.put("gameareaId", oneServerJson.getString("id"));
                        params.put("gameareaName", oneServerJson.getString("name"));
                    }
                }
            }
        }
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        // 创建一个Map，用于存储需要排序并加密的数据
        Map<String, Object> dataMap = new TreeMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        dataMap.put("goodsId", artRecs.get(0).getOutid());
        dataMap.put("appKey", salePartner.getOther());
        dataMap.put("timestamp", time);
        // 遍历排序后的Map，将value值拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            stringBuilder.append(entry.getValue());
        }
        // 执行SHA-256加密
        String encryptedData = DigestUtil.sha256Hex(stringBuilder.toString());
        dataMap.remove("timestamp");
        dataMap.remove("appKey");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appId", salePartner.getSaleKey());
        paramMap.put("timestamp", time);
        paramMap.put("sign", encryptedData);
        paramMap.put("data", dataMap);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-Type", "application/json; charset=UTF-8");
        String response = HttpRequest.post("https://www.taohaowan.com/prod-api/system-api/gamesInfo/gameTakedown").body(JSONObject.toJSONString(paramMap)).execute().body();
        if (StringUtils.isEmpty(response)) {
            throw new GlobalException("请求接口失败");
        }
        log.info("淘号玩删除接口返回参数={}", JSONObject.toJSONString(response));
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();
        ArtRec artRec = artRecs.get(0);
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        artRecMapper.updateArtRec(artRec);
        result.put("req", JSONObject.toJSONString(paramMap));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }


    private static String getRea() {
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        // 创建一个Map，用于存储需要排序并加密的数据
        Map<String, Object> dataMap = new TreeMap<>();
        dataMap.put("gameId", "5ed2e37abe2249f5a5d6f9d7e0d13dfb");//查询游戏ID
        dataMap.put("appKey", "4qBfmlr1WqGrJ5AMYtNtVy8_5ovHkRZUC49d8lkB3tY");
        dataMap.put("timestamp", time);
        // 遍历排序后的Map，将value值拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            stringBuilder.append(entry.getValue());
        }
        // 执行SHA-256加密
        String encryptedData = DigestUtil.sha256Hex(stringBuilder.toString());
        dataMap.remove("timestamp");
        dataMap.remove("appKey");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appId", "7d961bad4b334c0688cef8911347e8bf");
        paramMap.put("timestamp", time);
        paramMap.put("sign", encryptedData);
        paramMap.put("data", dataMap);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-Type", "application/json; charset=UTF-8");
        String response = HttpUtils.sendPost("https://test-www.taohaowan.com/prod-api/system-api/gamesInfo/gameAreaSearch", JSONObject.toJSONString(paramMap), "application/json");
        return response;
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    public static void main(String[] args) {
//        String time = String.valueOf(System.currentTimeMillis() / 1000);
//        // 创建一个Map，用于存储需要排序并加密的数据
//        Map<String, Object> dataMap = new TreeMap<>();
////        dataMap.put("goodsId", "1688628970022");//查询游戏ID
//        dataMap.put("appKey", "4qBfmlr1WqGrJ5AMYtNtVy8_5ovHkRZUC49d8lkB3tY");
//        dataMap.put("timestamp", time);
//        // 遍历排序后的Map，将value值拼接
//        StringBuilder stringBuilder = new StringBuilder();
//        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
//            stringBuilder.append(entry.getValue());
//        }
//        // 执行SHA-256加密
//        String encryptedData = DigestUtil.sha256Hex(stringBuilder.toString());
//        dataMap.remove("timestamp");
//        dataMap.remove("appKey");
//
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("appId", "7d961bad4b334c0688cef8911347e8bf");
//        paramMap.put("timestamp", time);
//        paramMap.put("sign", encryptedData);
//        paramMap.put("data", dataMap);
//        Map<String, Object> header = new HashMap<>();
//        header.put("Content-Type", "application/json; charset=UTF-8");
//        String response = HttpUtils.sendPost("https://test-www.taohaowan.com/prod-api/system-api/gamesInfo/gameSearch", JSONObject.toJSONString(paramMap), "application/json");
//        log.info(response);
        SalePartner salePartner = new SalePartner();
        salePartner.setOther("iWNo8M1ZC8xD89ryUmtIm3WELQhK6sdgH+ZhxZIXWpI=");
        salePartner.setSaleKey("e573ec6ce2d14f6fb791ab7ff42e571d");
        String games = getAttr("2e6581c93f85462a94023e94cf92a24d",salePartner);
//        String games = getGames();
        System.out.println(games);
    }

    private static String getAttr(String gameId, SalePartner salePartner) {
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        // 创建一个Map，用于存储需要排序并加密的数据
        Map<String, Object> dataMap = new TreeMap<>();
        dataMap.put("gameId", gameId);//查询游戏ID
        dataMap.put("appKey", salePartner.getOther());
        dataMap.put("timestamp", time);
        // 遍历排序后的Map，将value值拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            stringBuilder.append(entry.getValue());
        }
        // 执行SHA-256加密
        String encryptedData = DigestUtil.sha256Hex(stringBuilder.toString());
        dataMap.remove("timestamp");
        dataMap.remove("appKey");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appId", salePartner.getSaleKey());
        paramMap.put("timestamp", time);
        paramMap.put("sign", encryptedData);
        paramMap.put("data", dataMap);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-Type", "application/json; charset=UTF-8");
        String response = HttpUtils.sendPost("https://www.taohaowan.com/prod-api/system-api/gamesInfo/getGameAttr", JSONObject.toJSONString(paramMap), "application/json");
        return response;
    }

    private static String getArea(String gameId, SalePartner salePartner) {
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        // 创建一个Map，用于存储需要排序并加密的数据
        Map<String, Object> dataMap = new TreeMap<>();
        dataMap.put("gameId", gameId);//查询游戏ID
        dataMap.put("appKey", salePartner.getOther());
        dataMap.put("timestamp", time);
        // 遍历排序后的Map，将value值拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            stringBuilder.append(entry.getValue());
        }
        // 执行SHA-256加密
        String encryptedData = DigestUtil.sha256Hex(stringBuilder.toString());
        dataMap.remove("timestamp");
        dataMap.remove("appKey");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appId", salePartner.getSaleKey());
        paramMap.put("timestamp", time);
        paramMap.put("sign", encryptedData);
        paramMap.put("data", dataMap);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-Type", "application/json; charset=UTF-8");
        String response = HttpUtils.sendPost("https://www.taohaowan.com/prod-api/system-api/gamesInfo/gameAreaSearch", JSONObject.toJSONString(paramMap), "application/json");
        return response;
    }

    static String getGames(){
        String url = "https://www.taohaowan.com/prod-api/system-api/gamesInfo/gameSearch";
        String appId = "e573ec6ce2d14f6fb791ab7ff42e571d";
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> dataMap = new TreeMap<>();
        dataMap.put("appKey", "iWNo8M1ZC8xD89ryUmtIm3WELQhK6sdgH+ZhxZIXWpI=");
        dataMap.put("timestamp", time);
        // 遍历排序后的Map，将value值拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            stringBuilder.append(entry.getValue());
        }
        // 执行SHA-256加密
        String encryptedData = DigestUtil.sha256Hex(stringBuilder.toString());
        dataMap.remove("timestamp");
        dataMap.remove("appKey");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appId", appId);
        paramMap.put("timestamp", time);
        paramMap.put("sign", encryptedData);
        paramMap.put("data", dataMap);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-Type", "application/json; charset=UTF-8");
        String response = HttpUtils.sendPost(url, JSONObject.toJSONString(paramMap), "application/json");
        return response;
    }

}
